package com.linshidream.intrachat.simplenio.pipeline.hearbeat;

import com.linshidream.intrachat.simplenio.pipeline.context.MiniHandlerContext;
import com.linshidream.intrachat.simplenio.pipeline.handler.MiniChannelInboundHandler;
import com.linshidream.intrachat.simplenio.pipeline.handler.MiniChannelOutboundHandler;

/**
 * Created on 2025/8/21 18:30
 *
 * @author linshidream
 * @version 1.0.0
 * @description 空闲时间处理器
 * <p>同时监听读和写的事件，然后超过最大时间发布自定义事件<p/>
 */

public class MiniIdleStateHandler implements MiniChannelInboundHandler, MiniChannelOutboundHandler {

    /**
     * 读空闲时间（两次读之间的空闲时间）
     */
    private final long readerIdleTime;

    /**
     * 写空闲时间（两次写之间的空闲时间）
     */
    private final long writerIdleTime;

    /**
     * 最后一次读的时间
     */
    private long lastReadTime;

    /**
     * 最后一次写的时间
     */
    private long lastWriteTime;

    /**
     * 单位 毫秒
     *
     * @param readerIdleTime
     * @param writerIdleTime
     */
    public MiniIdleStateHandler(long readerIdleTime, long writerIdleTime) {
        this.readerIdleTime = readerIdleTime;
        this.writerIdleTime = writerIdleTime;
        this.lastReadTime = System.currentTimeMillis();
        this.lastWriteTime = System.currentTimeMillis();
    }


    @Override
    public void channelRead(MiniHandlerContext ctx, Object msg) {
        // 更新最近一次读的时间
        lastReadTime = System.currentTimeMillis();
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelWrite(MiniHandlerContext ctx, Object msg) {
        // 更新最近一次写的时间
        lastWriteTime = System.currentTimeMillis();
        ctx.fireWrite(msg);
    }

    public void checkIdle(MiniHandlerContext ctx) {
        long now = System.currentTimeMillis();

        // 读事件空闲
        if (now - lastReadTime > readerIdleTime) {
            System.out.println("[MiniIdleStateHandler] 空闲检测超时，已触发读空闲事件");
            ctx.fireUserEventTriggered(MiniIdleState.READ_IDLE);
        }
        // 写事件空闲
        if (now - lastWriteTime > writerIdleTime) {
            System.out.println("[MiniIdleStateHandler] 空闲检测超时，已触发写空闲事件");
            ctx.fireUserEventTriggered(MiniIdleState.WRITE_IDLE);
        }
    }
}